// pages/placeOrder/placeorder.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    lastTatalPrice: 0, //最后的总价
    selectYqh: '请选择', //抵扣信息
    yhqId: null, //选中的优惠券id
    add_res: null, //地址信息
    isGroup: false,  //判断是否拼团
    isActive: false
  },
 
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let data;
    wx.showLoading({ title: '加载中', mask: true });
    switch (options.type) {
      //从商品详情进入确认订单页面
      case "1": 
        data = {
          type: 1,
          item_id: options.item_id,
          gui_id: options.gui_id,
          item_num: options.item_num,
          user_id: app.globalData.userId
        };
        break;
      case "3": 
        this.setData({
          isActive: true
        });  //判断是否活动订单
        data = {
          type: 1,
          item_id: options.item_id,
          gui_id: options.gui_id,
          item_num: options.item_num,
          user_id: app.globalData.userId
        };
        break;

      // 拼团  --->  开团购买
      case "4":
        const info = JSON.parse(options.info);
        const _pid=info.pid?true:false;
        this.setData({
          groupData: info,
          isGroup: _pid,
          isActive: _pid
        });
        data = {
          type: 1,
          item_id: info.item_id,
          gui_id: info.gui_id,
          item_num: info.item_num,
          a_id: info.a_id,
          user_id: app.globalData.userId,
          pid: info.pid,
          activity_id: 37
        };
        break;

        // 拼团 --->  单独购买
      case "5":
        const info1 = JSON.parse(options.info);
        data = {
          type: 1,
          item_id: info1.item_id,
          gui_id: info1.gui_id,
          item_num: info1.item_num,
          user_id: app.globalData.userId
        };
        break;

      //从购物车进入确认订单页面
      case "2": 
        data = {
          type: 2,
          cart_id: JSON.parse(options.cart_ids).join(','),
          user_id: app.globalData.userId
        };
        break;
      default:
        return;  
    };
    //发送下单请求
    wx.request({
      url: app.baseURL + 'Shopping&a=index',
      data: data,
      success: res => {
        if (res.statusCode == 200 && res.data.status == 1) {
          const data = res.data['0'];
          data.realPrice = (Number(data.total_price) + Number(data.yunfei)).toFixed(2);
          this.setData({
            info: data,
            add_res: data.add_res
          });
          wx.hideLoading();
        }
        if (res.data.status == 5){
          wx.hideLoading();
          wx.showModal({
            title: '提示',
            content: "当前商品存在未支付的订单,是否前往支付?",
            success: function (res) {
              if (res.confirm) {
                wx.navigateTo({
                  url: '/pages/order/order?jk=wait_pay&type=1'
                })
              }
            }
          })
        }
        if (res.data.status == 2){
          wx.showToast({
            title: res.data.info,
            icon: 'none'
          });
          setTimeout(function(){
            wx.navigateBack({
              delta: 1
            })
          },800)
        }
      }
    });
    this.setData({
      fromType: options.type
    })
  },

  //选择优惠券后重新计算商品总价
  getTotalPrice(reduceMoney){
    let realPrice = this.data.info.yunfei + this.data.info.total_price - reduceMoney; //商品金额+运费-优惠券=实际金额
    this.setData({
      ["info.realPrice"]: realPrice.toFixed(2)
    });
  },

  //点击提交按钮
  submitOrder(e) {
    let formid = e.detail.formId;
    let data, url; 
    //如果没有添加收货地址提醒用户添加收货地址
    if (!this.data.add_res) { wx.showToast({ title: '请添加收货地址', icon: 'none' }); return; }
    //如果是从商品详情直接下单
    if (this.options.type != 2) {
      url = app.baseURL + 'Shopping&a=atOnceOrder';
      data = {
        item_num: this.data.info.total_num, //商品数量
        address_id: this.data.add_res.id, //地址id
        gui_id: this.data.info.item_info.gui_id,// 规格id
        yhq_id: this.data.yhqId, //优惠券id
        item_id: this.data.info.item_info.id, //商品id
        user_id: app.globalData.userId, //用户id
        form_id: formid,   //formId
      }
      if (this.data.isGroup){
        data.activity_id = 37;
        data.pid = this.data.groupData.pid,
        data.a_id = this.data.groupData.a_id
      }
    //如果是从购物车下单
    } else if (this.options.type == 2) {
      data = {
        address_id: this.data.add_res.id, //地址id
        cart_id: JSON.parse(this.options.cart_ids).join(','), //购物车id,将数组转换成字符串
        yhq_id: this.data.yhqId, //优惠券id
        user_id: app.globalData.userId, //用户id
        form_id: formid,   //formId
      };
      url = app.baseURL + 'Shopping&a=cartOrder';
    }
    //如果用户有备注，则提交备注字段
    e.detail.value.message && (data.comment = e.detail.value.message); 
    
    if (this.data.etc){
      console.log("等下");
      return;
    }
    this.setData({etc: true})

    wx.showLoading({ title: '请稍后', mask: true });
    //发送下单请求
    wx.request({
      url: url,
      data: data,
      success: (res) => {
        if (res.data.status == 0 ){
          wx.showToast({
            title: res.data.info,
            icon: 'none'
          })
        }
        if (res.data.status == 1 && res.statusCode == 200) {
          wx.hideLoading();
          //跳转支付页面
          let result = JSON.stringify(res.data.order_info);
          // 如果是砍价下单，传type标识
          let url = '/pages/orderPay/orderPay?result=' + result + '&isSetPass=' + res.data.is_set_pass;
          if (this.options.type == 3) {
            url = '/pages/orderPay/orderPay?result=' + result + '&isSetPass=' + res.data.is_set_pass + "&type=3";
          }
          if (this.options.type == 4) {
            url = '/pages/orderPay/orderPay?result=' + result + '&isSetPass=' + res.data.is_set_pass + "&pid=" + this.data.groupData.pid;
          }
          wx.redirectTo({
            url: url
          })
        }else{
          wx.showToast({
            title: res.data.info,
            icon: "none"
          })
        }
      },
      complete: (res => {
        console.log("好了");
        this.setData({ etc: false })
      })
    })
    
  },

  //前往添加收货地址
  toAddAddress() {
    wx.navigateTo({
      url: '/pages/addressAdd/addressAdd?formWeb=order',
    })
  },

  //去选择收货地址
  selectAddress() {
    wx.navigateTo({
      url: '/pages/address/address?select=true',
    })
  },

  // 去选择优惠券
  selectCoupon(e) {
    let list = e.currentTarget.dataset.list;
    if (!list.length) { return }
    let list_json = JSON.stringify(list);
    wx.navigateTo({
      url: '/pages/useCoupon/useCoupon?list=' + list_json,
    });
  }
})